package handler

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"onechat/api/service"
	"onechat/golbal"
	"onechat/model"
)

func Create(c *gin.Context) {
	req := service.UserReq{}
	err := c.ShouldBind(&req)
	if err != nil {
		fmt.Errorf("绑定失败")
	}

	user := model.User{

		Account:  req.Account,
		Password: req.Password,
	}
	golbal.DB.Debug().Create(&user)

	c.JSON(http.StatusOK, gin.H{

		"code": 200,
		"msg":  "用户信息创建成功",
	})

}

func FriendAdd(c *gin.Context) {
	add := service.FriedReq{}
	err := c.ShouldBind(&add)
	if err != nil {
		fmt.Errorf("绑定失败")
	}

	friend := model.Friend{

		UserId:   uint(add.UserId),
		FriendId: uint(add.FriendId),
	}
	golbal.DB.Debug().Create(&friend)

	c.JSON(http.StatusOK, gin.H{

		"code": 200,
		"msg":  "好友添加成功",
	})
}

func Show(c *gin.Context) {

	show := service.UserReq{}
	err := c.ShouldBind(&show)
	if err != nil {
		fmt.Errorf("绑定失败")
	}

	page := show.Page
	if page <= 0 {
		page = 1
	}

	pageSize := show.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize
	var user model.User

	golbal.DB.Debug().Where("account=?", show.Account).Offset(int(offset)).Find(&user)

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "查询成功",
	})

}
